import * as signalR from '@microsoft/signalr'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

class SignalRService {
  constructor() {
    this.connection = null
    this.messageHandlers = []
    this.typingHandlers = []
    this.userJoinedHandlers = []
    this.userLeftHandlers = []
    this.errorHandlers = []
  }

  // 初始化连接
  async startConnection() {
    try {
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl('/Hubs/GroupChatHub', {
          accessTokenFactory: () => getToken()
        })
        .withAutomaticReconnect()
        .build()

      // 注册事件处理程序
      this.registerEventHandlers()

      // 启动连接
      await this.connection.start()
      console.log('SignalR Connected')
      return true
    } catch (err) {
      console.error('SignalR Connection Error: ', err)
      Message.error('聊天服务连接失败，请刷新页面重试')
      return false
    }
  }

  // 注册事件处理程序
  registerEventHandlers() {
    // 接收消息
    this.connection.on('ReceiveMessage', (data) => {
      this.messageHandlers.forEach(handler => handler(data))
    })

    // 用户正在输入
    this.connection.on('UserTyping', (data) => {
      this.typingHandlers.forEach(handler => handler(data))
    })

    // 用户加入群组
    this.connection.on('UserJoined', (data) => {
      this.userJoinedHandlers.forEach(handler => handler(data))
    })

    // 用户离开群组
    this.connection.on('UserLeft', (data) => {
      this.userLeftHandlers.forEach(handler => handler(data))
    })

    // 错误处理
    this.connection.on('Error', (message) => {
      console.error('SignalR Error:', message)
      this.errorHandlers.forEach(handler => handler(message))
      Message.error(message)
    })

    // 连接关闭
    this.connection.onclose(async () => {
      console.log('SignalR Connection Closed')
      Message.warning('聊天服务连接已断开，正在尝试重新连接...')
      setTimeout(async () => {
        await this.startConnection()
      }, 5000)
    })
  }

  // 加入群组
  async joinGroup(groupId) {
    try {
      if (this.connection && this.connection.state === signalR.HubConnectionState.Connected) {
        await this.connection.invoke('JoinGroup', groupId)
        console.log(`Joined group: ${groupId}`)
        return true
      } else {
        console.error('SignalR not connected')
        return false
      }
    } catch (err) {
      console.error('Join Group Error:', err)
      return false
    }
  }

  // 离开群组
  async leaveGroup(groupId) {
    try {
      if (this.connection && this.connection.state === signalR.HubConnectionState.Connected) {
        await this.connection.invoke('LeaveGroup', groupId)
        console.log(`Left group: ${groupId}`)
        return true
      } else {
        console.error('SignalR not connected')
        return false
      }
    } catch (err) {
      console.error('Leave Group Error:', err)
      return false
    }
  }

  // 发送消息
  async sendMessage(groupId, content) {
    try {
      if (this.connection && this.connection.state === signalR.HubConnectionState.Connected) {
        await this.connection.invoke('SendMessage', groupId, content)
        return true
      } else {
        console.error('SignalR not connected')
        return false
      }
    } catch (err) {
      console.error('Send Message Error:', err)
      return false
    }
  }

  // 发送正在输入状态
  async sendTyping(groupId) {
    try {
      if (this.connection && this.connection.state === signalR.HubConnectionState.Connected) {
        await this.connection.invoke('Typing', groupId)
        return true
      } else {
        console.error('SignalR not connected')
        return false
      }
    } catch (err) {
      console.error('Send Typing Error:', err)
      return false
    }
  }

  // 添加消息处理程序
  onMessage(handler) {
    this.messageHandlers.push(handler)
  }

  // 添加正在输入处理程序
  onTyping(handler) {
    this.typingHandlers.push(handler)
  }

  // 添加用户加入处理程序
  onUserJoined(handler) {
    this.userJoinedHandlers.push(handler)
  }

  // 添加用户离开处理程序
  onUserLeft(handler) {
    this.userLeftHandlers.push(handler)
  }

  // 添加错误处理程序
  onError(handler) {
    this.errorHandlers.push(handler)
  }

  // 移除所有处理程序
  removeAllHandlers() {
    this.messageHandlers = []
    this.typingHandlers = []
    this.userJoinedHandlers = []
    this.userLeftHandlers = []
    this.errorHandlers = []
  }

  // 停止连接
  async stopConnection() {
    try {
      if (this.connection) {
        await this.connection.stop()
        console.log('SignalR Disconnected')
      }
    } catch (err) {
      console.error('SignalR Stop Error:', err)
    }
  }
}

// 创建单例
const signalRService = new SignalRService()
export default signalRService 